<template>
  <div class="bgff p20">
    <em v-if="0">
      <el-button class="mb20" size="medium" type="primary" @click="addNet">添加角色</el-button>
      <!-- <el-button class="mb20" size="medium" type="primary" @click="expandFn">展开</el-button> -->
      <edit :is_edit="false" ref="form" :cur_this="cur_this"></edit>
    </em>
    <el-row :gutter="15" style="margin-top:20px;">
      <!--角色管理-->
      <el-col :xs="24" :sm="24" :md="16" :lg="16" :xl="17">
        <el-card class="box-card" shadow="never">
          <div slot="header" class="clearfix">
            <span class="role-span">角色列表</span>
            <div id="opt" style="float: right">
              <el-radio-group v-model="opt" size="mini">
                <el-radio-button label="菜单分配" />
                <el-radio-button label="权限分配" />
              </el-radio-group>
            </div>
          </div>
          <el-table
            v-loading="loading"
            :data="tableData"
            highlight-current-row
            size="small"
            style="width: 100%;"
            @current-change="handleCurrentChange"
          >
            <el-table-column prop="name" label="角色名称" />
            <el-table-column prop="dataScope" label="数据权限" />
            <el-table-column prop="level" label="角色级别" />
            <el-table-column prop="remark" label="描述"></el-table-column>
            <el-table-column :show-overflow-tooltip="true" prop="createTime" label="创建日期">
              <template slot-scope="scope">
                {{new Date(scope.row.createTime).format('yy-MM-dd hh:mm:ss')}}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="80px" v-if="0">
              <template slot-scope="scope">
                <em>
                  <el-button @click="editClick(scope.row)" type="text" size="small">编辑</el-button>
                  <edit :is_edit="true" :cur_this="cur_this" ref="edform"></edit>
                </em>
                <el-popover :ref="scope.row.id" placement="top" width="180">
                  <p>确定删除本条数据吗？</p>
                  <div style="text-align: right; margin: 0">
                    <el-button size="mini" type="text" @click="$refs[scope.row.id].doClose()">取消</el-button>
                    <el-button
                      :loading="delLoading"
                      type="primary"
                      size="mini"
                      @click="del(scope.row.id)"
                    >确定</el-button>
                  </div>
                   <el-button slot="reference" type="text" size="mini">删除</el-button>
                </el-popover>
              </template>
            </el-table-column>
          </el-table>
          <!--分页组件-->
          <el-pagination
            class="mt20"
            @current-change="handlePage"
            @size-change="handleSizeChange"
            :current-page.sync="curPage"
            :page-size="size"
            :page-sizes="[5,10]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
          ></el-pagination>
        </el-card>
      </el-col>
      <!-- 授权 -->
      <el-col :xs="24" :sm="24" :md="8" :lg="8" :xl="7">
        <el-card v-show="opt === '菜单分配'" class="box-card" shadow="never">
          <div slot="header" class="clearfix">
            <el-tooltip class="item" effect="dark" content="选择指定角色分配菜单" placement="top">
              <span class="role-span">菜单分配</span>
            </el-tooltip>
            <el-button
              :disabled="!showButton"
              :loading="menuLoading"
              icon="el-icon-check"
              size="mini"
              style="float: right; padding: 6px 9px"
              type="primary"
              @click="saveMenu"
            >保存</el-button>
          </div>
          <el-tree
            ref="menu"
            :data="menus"
            :default-checked-keys="menuIds"
            :props="defaultProps"
            accordion
            show-checkbox
            node-key="id"
          />
        </el-card>
        <el-card v-show="opt === '权限分配'" class="box-card" shadow="never">
          <div slot="header" class="clearfix">
            <el-tooltip class="item" effect="dark" content="选择指定角色分配权限" placement="top">
              <span class="role-span">权限分配</span>
            </el-tooltip>
            <el-button
              :disabled="!showButton"
              :loading="permissionLoading"
              icon="el-icon-check"
              size="mini"
              style="float: right; padding: 6px 9px"
              type="primary"
              @click="savePermission"
            >保存</el-button>
          </div>
          <el-tree
            ref="permission"
            :data="permissions"
            :default-checked-keys="permissionIds"
            :props="defaultProps"
            show-checkbox
            accordion
            node-key="id"
          />
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import {
  _rolesList,
  _rolesShow,
  _menusAll,
  _rolesUpdateMenu,
  _rolesUpdatePermission,
  _permissionsAll,
  _rolesDelete
} from "@/http/ajax";
// import checkPermission from '@/utils/permission'
// import initData from '@/mixins/initData'
// import { del } from '@/api/role'
// import { getPermissionTree } from '@/api/permission'
// import { parseTime } from '@/utils/index'
// import eHeader from './module/header'
import edit from "./modul/edit";
// import { editPermission, editMenu, get } from '@/api/role'
export default {
  components: { edit },
  data() {
    return {
      cur_this: this,
      curPage: 1,
      size: 10,
      total: 0,
      loading: false,
      tableData: [],
      menus: [],
      menuIds: [],

      defaultProps: {
        children: "children",
        label: "label"
      },
      currentId: 0,
      permissionLoading: false,
      menuLoading: false,
      showButton: false,
      opt: "菜单分配",
      delLoading: false,
      sup_this: this,
      permissions: [],
      permissionIds: []
    };
  },
  created() {
    this.getList();
    this.getMenus();
    this.getPermissions();
  },
  methods: {
    getMenus() {
      _menusAll(
        res => {
          this.menus = res;
        },
        err => {}
      );
    },
    getList() {
      let data = {
        page: this.curPage - 1,
        size: this.size
      };
      _rolesList(
        data,
        res => {
          setTimeout(() => {
            this.total = res.totalElements;
            this.tableData = res.content;
            this.loading = false;
          }, 300);
        },
        err => {}
      );
    },
    // 切换页码
    handlePage(val) {
      this.curPage = val;
      this.getList();
    },
    // 切换条数
    handleSizeChange(val) {
      this.curPage = 1;
      this.size = val;
      this.getList();
    },
    editClick(row) {
      const _this = this.$refs.edform;
      _this.dialog = true;
      _this.form = {
        name: row.name,
        depts: row.depts,
        remark: row.remark,
        dataScope: row.dataScope,
        level: row.level,
        id: row.id
      };
      for (let i = 0; i < _this.form.depts.length; i++) {
        _this.deptIds[i] = _this.form.depts[i].id
      }
      _this.domInit();
    },
    addNet() {
      const _this = this.$refs.form;
      _this.dialog = true;
      _this.domInit();
    },
    beforeInit() {
      this.$refs.permission.setCheckedKeys([]);
      this.$refs.menu.setCheckedKeys([]);
      this.showButton = false;
      this.url = "api/roles";
      const sort = "level,asc";
      const query = this.query;
      const value = query.value;
      this.params = { page: this.page, size: this.size, sort: sort };
      if (value) {
        this.params["name"] = value;
      }
      return true;
    },
    del(id) {
      this.delLoading = true;
      _rolesDelete(
        id,
        res => {
          this.delLoading = false;
          this.$notify({
            title: "删除成功",
            type: "success",
            duration: 2500
          });
          this.getList();
        },
        err => {
          this.delLoading = false;
          // console.log(err.response.data.message);
        }
      );
    },
    getPermissions() {
      _permissionsAll(
        res => {
          this.permissions = res;
        },
        err => {}
      );
    },

    handleCurrentChange(val) {
      if (val) {
        const _this = this;
        // 清空权限与菜单的选中
        this.$refs.permission.setCheckedKeys([]);
        this.$refs.menu.setCheckedKeys([]);
        // 保存当前的角色id
        this.currentId = val.id;
        // 点击后显示按钮
        this.showButton = true;
        // 初始化
        this.menuIds = [];
        this.permissionIds = [];
        // 菜单数据需要特殊处理
        val.menus.forEach(function(data, index) {
          let add = true;
          for (let i = 0; i < val.menus.length; i++) {
            if (data.id === val.menus[i].pid) {
              add = false;
              break;
            }
          }
          if (add) {
            _this.menuIds.push(data.id);
          }
        });
        // 处理权限数据
        val.permissions.forEach(function(data, index) {
          _this.permissionIds.push(data.id);
        });
      }
    },
    savePermission() {
      this.permissionLoading = true;
      const role = { id: this.currentId, permissions: [] };
      this.$refs.permission.getCheckedKeys().forEach(function(data, index) {
        const permission = { id: data };
        role.permissions.push(permission);
      });
      _rolesUpdatePermission(
        role,
        res => {
          this.$notify({
            title: "保存成功",
            type: "success",
            duration: 2500
          });
          this.permissionLoading = false;
          this.update();
        },
        err => {
          this.permissionLoading = false;
          console.log(err.response.data.message);
        }
      );
    },
    saveMenu() {
      this.menuLoading = true;
      const role = { id: this.currentId, menus: [] };
      // 得到半选的父节点数据，保存起来
      this.$refs.menu.getHalfCheckedNodes().forEach(function(data, index) {
        const permission = { id: data.id };
        role.menus.push(permission);
      });
      // 得到已选中的 key 值
      this.$refs.menu.getCheckedKeys().forEach(function(data, index) {
        const permission = { id: data };
        role.menus.push(permission);
      });
      _rolesUpdateMenu(
        role,
        res => {
          this.$notify({
            title: "保存成功",
            type: "success",
            duration: 2500
          });
          this.menuLoading = false;
          this.update();
        },
        err => {
          this.menuLoading = false;
          console.log(err.response.data.message);
        }
      );
    },
    update() {
      // 无刷新更新 表格数据
      _rolesShow(
        this.currentId,
        res => {
          for (let i = 0; i < this.tableData.length; i++) {
            if (res.id === this.tableData[i].id) {
              this.tableData[i] = res;
              break;
            }
          }
        },
        err => {}
      );
    }
  }
};
</script>

<style rel="stylesheet/scss" lang="scss">
.role-span {
  font-weight: bold;
  color: #303133;
  font-size: 15px;
}
</style>
